//
//  NDContactsViewModel.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/31.
//

import UIKit
import Combine
import SwiftUI

class NDContactsViewModel: ObservableObject {
    @Published var contactsModel: ContactsModel?
    @Published var isLoading = false
    @Published var errorMessage: String?
    @Published var commonActionSectionIndex = 0
    @Published var saveSuccess = false
    
    var isUploadEvent = false
    
    let productId: Int
    var orderNum: String?
    var startTimeStamp = 0
    
    init(productId: Int, orderNum: String) {
        self.productId = productId
        self.orderNum = orderNum
    }

    func loadContactsData() {
        isLoading = true
        errorMessage = nil

        NDRequestManager.requestContacts(productId: productId) { [weak self] contacts, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.isLoading = false
                
                if let error = error {
                    self.errorMessage = msg
                    print("请求失败: \(error)")
                    return
                }
                
                guard let contacts = contacts else {
                    self.errorMessage = "no data"
                    return
                }
                
                self.contactsModel = contacts
            }
        }
    }
    
    func saveContactsData() {
        isLoading = true
        errorMessage = nil
        guard let pachists = contactsModel?.egrirecognizeic?.pachist else { return }
        NDRequestManager.requestSaveContactsInfo(productId: productId, pachists: pachists) { [weak self] success, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {

                if let error = error {
                    self.errorMessage = msg
                    print("请求失败: \(error)")
                    self.isLoading = false
                    return
                }
                guard let success = success else {
                    self.errorMessage = "failed"
                    self.isLoading = false
                    return
                }
                
                self.isLoading = false
                self.saveSuccess = success
                NDEventAnallyticsTool.uploadMaiDianEvent(maiDianType: .contactCard,
                                                         productId: self.productId,
                                                         orderNum: self.orderNum,
                                                         startTimeStamp: self.startTimeStamp,
                                                         endTimeStamp: Int(Date().timeIntervalSince1970))
            }
        }
    }
    
    func createPachistBinding(at index: Int, field: PachistNum) -> Binding<String> {
        return Binding(
            get: {
                guard let pachist = self.contactsModel?.egrirecognizeic?.pachist,
                      index < pachist.count else { return "" }
                
                return self.getValueForField(pachist[index], field: field)
            },
            set: { newValue in
                self.updateEnergyifyField(at: index, field: field, value: newValue)
            }
        )
    }
    
    // 获取字段值
    private func getValueForField(_ pachist: Pachist, field: PachistNum) -> String {
        switch field {
        case .pressoutside, .interestacle:
            let interestacleText = pachist.interestacle ?? ""
            let pressoutsideText = pachist.pressoutside ?? ""
            
            // 只有当两个字符串都不为空时才用连字符连接
            if !interestacleText.isEmpty && !pressoutsideText.isEmpty {
                return interestacleText + "-" + pressoutsideText
            } else {
                // 如果有一个为空，就返回非空的那个，或者空字符串
                return interestacleText + pressoutsideText
            }
            
        case .olig:
            var text = ""
            if let piouswise = Int(pachist.piouswise ?? "-1"),
               let communityents = pachist.communityent {
                
                let communityents = communityents.filter { $0.olig == "\(piouswise)" }
                text = communityents.first?.interestacle ?? ""
            }
            return text
        }
    }
    
    // 更新 energyify 中特定字段的方法
    func updateEnergyifyField(at index: Int, field: PachistNum, value: String) {
        guard var model = contactsModel,
              var egrirecognizeic = model.egrirecognizeic,
              let pachist = egrirecognizeic.pachist,
              index < pachist.count else {
            print("Error: Data not available or index out of bounds")
            return
        }
        
        // 创建 pachist 数组的可变副本
        var updatedPachist = pachist
        
        // 根据字段类型更新对应的值
        switch field {
        case .pressoutside:
            updatedPachist[index].pressoutside = value
        case .interestacle:
            updatedPachist[index].interestacle = value
        case .olig:
            updatedPachist[index].piouswise = value
        }
        
        // 逐层更新回原始模型
        egrirecognizeic.pachist = updatedPachist
        model.egrirecognizeic = egrirecognizeic
        contactsModel = model
        
        print("Updated field \(field) at index \(index) to: \(value)")
    }
    
    // 定义字段枚举
    enum PachistNum {
        case pressoutside // 电话号码
        case interestacle // 姓名
        case olig
    }
    
    var courseatics: [Courseatic] {
        if let pachist = contactsModel?.egrirecognizeic?.pachist,
           pachist.count > commonActionSectionIndex {
            return pachist[commonActionSectionIndex].communityent ?? []
        }
        return []
    }
    
    var title: String {
        if let pachist = contactsModel?.egrirecognizeic?.pachist,
           pachist.count > commonActionSectionIndex {
            return pachist[commonActionSectionIndex].himselfful ?? ""
        }
        return ""
    }
}

